<template>
  <div class="quality-management">
    <!-- 页面标题和操作 -->
    <div class="page-header">
      <div class="header-left">
        <h1>质量管理</h1>
        <p>产品质量检验、控制和不合格品处理</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="showCreateInspectionDialog">
          <el-icon><Plus /></el-icon>
          新建质检单
        </el-button>
        <el-button @click="showQualityReportDialog">
          <el-icon><Document /></el-icon>
          质量报告
        </el-button>
        <el-button @click="exportData">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 质量统计概览 -->
    <div class="stats-overview">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon total">
                <el-icon><Document /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ qualityStats.totalInspections }}</div>
                <div class="stats-label">总检验次数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon pass">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ qualityStats.passRate }}%</div>
                <div class="stats-label">合格率</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon defect">
                <el-icon><Warning /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ qualityStats.defectCount }}</div>
                <div class="stats-label">不合格品数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon improvement">
                <el-icon><TrendCharts /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ qualityStats.improvementRate }}%</div>
                <div class="stats-label">质量改进率</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 质量趋势图表 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <span>质量趋势分析</span>
          </template>
          <div ref="qualityTrendChart" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <span>缺陷类型分布</span>
          </template>
          <div ref="defectTypeChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 功能标签页 -->
    <el-card class="tabs-card">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <!-- 质检管理 -->
        <el-tab-pane label="质检管理" name="inspection">
          <div class="tab-content">
            <!-- 筛选条件 -->
            <div class="filter-section">
              <el-form :model="inspectionFilter" inline>
                <el-form-item label="检验单号">
                  <el-input
                    v-model="inspectionFilter.inspectionNo"
                    placeholder="请输入检验单号"
                    clearable
                    @input="handleInspectionSearch"
                  >
                    <template #prefix>
                      <el-icon><Search /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item label="产品名称">
                  <el-input
                    v-model="inspectionFilter.productName"
                    placeholder="请输入产品名称"
                    clearable
                    @input="handleInspectionSearch"
                  />
                </el-form-item>
                <el-form-item label="检验类型">
                  <el-select v-model="inspectionFilter.inspectionType" placeholder="全部" clearable @change="handleInspectionSearch">
                    <el-option label="进料检验" value="incoming" />
                    <el-option label="过程检验" value="process" />
                    <el-option label="成品检验" value="final" />
                    <el-option label="出货检验" value="outgoing" />
                  </el-select>
                </el-form-item>
                <el-form-item label="检验状态">
                  <el-select v-model="inspectionFilter.status" placeholder="全部" clearable @change="handleInspectionSearch">
                    <el-option label="待检验" value="pending" />
                    <el-option label="检验中" value="inspecting" />
                    <el-option label="已完成" value="completed" />
                    <el-option label="不合格" value="failed" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleInspectionSearch">
                    <el-icon><Search /></el-icon>
                    搜索
                  </el-button>
                  <el-button @click="resetInspectionFilter">
                    <el-icon><Refresh /></el-icon>
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- 质检单列表 -->
            <el-table
              :data="filteredInspections"
              style="width: 100%"
              @selection-change="handleInspectionSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="inspectionNo" label="检验单号" width="140" />
              <el-table-column prop="productName" label="产品名称" min-width="150" />
              <el-table-column prop="batchNo" label="批次号" width="120" />
              <el-table-column prop="inspectionType" label="检验类型" width="120">
                <template #default="{ row }">
                  <el-tag :type="getInspectionTypeColor(row.inspectionType)">{{ getInspectionTypeText(row.inspectionType) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="quantity" label="检验数量" width="100" align="center" />
              <el-table-column prop="sampleSize" label="抽样数量" width="100" align="center" />
              <el-table-column prop="inspector" label="检验员" width="100" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getInspectionStatusType(row.status)">{{ getInspectionStatusText(row.status) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="result" label="检验结果" width="100">
                <template #default="{ row }">
                  <el-tag v-if="row.result" :type="row.result === 'pass' ? 'success' : 'danger'">
                    {{ row.result === 'pass' ? '合格' : '不合格' }}
                  </el-tag>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column prop="inspectionDate" label="检验日期" width="180" />
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="viewInspection(row)">
                    查看
                  </el-button>
                  <el-button v-if="row.status === 'pending'" size="small" @click="startInspection(row)">
                    开始检验
                  </el-button>
                  <el-button v-if="row.status === 'inspecting'" type="success" size="small" @click="completeInspection(row)">
                    完成检验
                  </el-button>
                  <el-dropdown @command="handleInspectionCommand">
                    <el-button size="small">
                      更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item :command="{action: 'edit', row}">编辑</el-dropdown-item>
                        <el-dropdown-item :command="{action: 'print', row}">打印报告</el-dropdown-item>
                        <el-dropdown-item :command="{action: 'delete', row}" divided>删除</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </template>
              </el-table-column>
            </el-table>

            <div class="pagination-container">
              <el-pagination
                v-model:current-page="inspectionPagination.currentPage"
                v-model:page-size="inspectionPagination.pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="inspectionPagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleInspectionSizeChange"
                @current-change="handleInspectionCurrentChange"
              />
            </div>
          </div>
        </el-tab-pane>

        <!-- 不合格品管理 -->
        <el-tab-pane label="不合格品管理" name="defect">
          <div class="tab-content">
            <!-- 筛选条件 -->
            <div class="filter-section">
              <el-form :model="defectFilter" inline>
                <el-form-item label="不合格品编号">
                  <el-input
                    v-model="defectFilter.defectNo"
                    placeholder="请输入编号"
                    clearable
                    @input="handleDefectSearch"
                  />
                </el-form-item>
                <el-form-item label="缺陷类型">
                  <el-select v-model="defectFilter.defectType" placeholder="全部" clearable @change="handleDefectSearch">
                    <el-option label="外观缺陷" value="appearance" />
                    <el-option label="尺寸偏差" value="dimension" />
                    <el-option label="功能缺陷" value="function" />
                    <el-option label="材料缺陷" value="material" />
                  </el-select>
                </el-form-item>
                <el-form-item label="处理状态">
                  <el-select v-model="defectFilter.handleStatus" placeholder="全部" clearable @change="handleDefectSearch">
                    <el-option label="待处理" value="pending" />
                    <el-option label="返工中" value="reworking" />
                    <el-option label="已报废" value="scrapped" />
                    <el-option label="已完成" value="completed" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleDefectSearch">
                    <el-icon><Search /></el-icon>
                    搜索
                  </el-button>
                  <el-button @click="resetDefectFilter">
                    <el-icon><Refresh /></el-icon>
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- 不合格品列表 -->
            <el-table
              :data="filteredDefects"
              style="width: 100%"
              @selection-change="handleDefectSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="defectNo" label="不合格品编号" width="140" />
              <el-table-column prop="productName" label="产品名称" min-width="150" />
              <el-table-column prop="defectType" label="缺陷类型" width="120">
                <template #default="{ row }">
                  <el-tag :type="getDefectTypeColor(row.defectType)">{{ getDefectTypeText(row.defectType) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="defectDescription" label="缺陷描述" min-width="200" />
              <el-table-column prop="quantity" label="数量" width="80" align="center" />
              <el-table-column prop="severity" label="严重程度" width="100">
                <template #default="{ row }">
                  <el-tag :type="getSeverityColor(row.severity)">{{ getSeverityText(row.severity) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="handleStatus" label="处理状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getHandleStatusType(row.handleStatus)">{{ getHandleStatusText(row.handleStatus) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="discoveryDate" label="发现日期" width="180" />
              <el-table-column label="操作" width="180" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="viewDefect(row)">
                    查看
                  </el-button>
                  <el-button v-if="row.handleStatus === 'pending'" size="small" @click="handleDefect(row)">
                    处理
                  </el-button>
                  <el-dropdown @command="handleDefectCommand">
                    <el-button size="small">
                      更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item :command="{action: 'edit', row}">编辑</el-dropdown-item>
                        <el-dropdown-item :command="{action: 'rework', row}" v-if="row.handleStatus === 'pending'">返工</el-dropdown-item>
                        <el-dropdown-item :command="{action: 'scrap', row}" v-if="row.handleStatus === 'pending'">报废</el-dropdown-item>
                        <el-dropdown-item :command="{action: 'delete', row}" divided>删除</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </template>
              </el-table-column>
            </el-table>

            <div class="pagination-container">
              <el-pagination
                v-model:current-page="defectPagination.currentPage"
                v-model:page-size="defectPagination.pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="defectPagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleDefectSizeChange"
                @current-change="handleDefectCurrentChange"
              />
            </div>
          </div>
        </el-tab-pane>

        <!-- 质量标准 -->
        <el-tab-pane label="质量标准" name="standard">
          <div class="tab-content">
            <div class="standard-header">
              <el-button type="primary" @click="showCreateStandardDialog">
                <el-icon><Plus /></el-icon>
                新建质量标准
              </el-button>
            </div>

            <el-table :data="qualityStandards" style="width: 100%">
              <el-table-column prop="standardCode" label="标准编码" width="120" />
              <el-table-column prop="standardName" label="标准名称" min-width="200" />
              <el-table-column prop="productCategory" label="产品类别" width="120" />
              <el-table-column prop="version" label="版本" width="80" align="center" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.status === 'active' ? 'success' : 'info'">{{ row.status === 'active' ? '启用' : '禁用' }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createDate" label="创建日期" width="180" />
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="viewStandard(row)">
                    查看
                  </el-button>
                  <el-button size="small" @click="editStandard(row)">
                    编辑
                  </el-button>
                  <el-button type="danger" size="small" @click="deleteStandard(row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 创建质检单对话框 -->
    <el-dialog
      v-model="inspectionDialogVisible"
      title="新建质检单"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="inspectionFormRef"
        :model="inspectionForm"
        :rules="inspectionRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="检验单号" prop="inspectionNo">
              <el-input v-model="inspectionForm.inspectionNo" placeholder="自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检验类型" prop="inspectionType">
              <el-select v-model="inspectionForm.inspectionType" placeholder="请选择检验类型" style="width: 100%">
                <el-option label="进料检验" value="incoming" />
                <el-option label="过程检验" value="process" />
                <el-option label="成品检验" value="final" />
                <el-option label="出货检验" value="outgoing" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-select v-model="inspectionForm.productName" placeholder="请选择产品" style="width: 100%">
                <el-option label="智能手机" value="智能手机" />
                <el-option label="平板电脑" value="平板电脑" />
                <el-option label="笔记本电脑" value="笔记本电脑" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批次号" prop="batchNo">
              <el-input v-model="inspectionForm.batchNo" placeholder="请输入批次号" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="检验数量" prop="quantity">
              <el-input-number v-model="inspectionForm.quantity" :min="1" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="抽样数量" prop="sampleSize">
              <el-input-number v-model="inspectionForm.sampleSize" :min="1" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="检验员" prop="inspector">
              <el-select v-model="inspectionForm.inspector" placeholder="请选择检验员" style="width: 100%">
                <el-option label="张三" value="张三" />
                <el-option label="李四" value="李四" />
                <el-option label="王五" value="王五" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检验日期" prop="inspectionDate">
              <el-date-picker
                v-model="inspectionForm.inspectionDate"
                type="datetime"
                placeholder="请选择检验日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="备注">
          <el-input
            v-model="inspectionForm.remarks"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="inspectionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveInspection">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 质量报告对话框 -->
    <el-dialog
      v-model="qualityReportVisible"
      title="质量报告"
      width="1000px"
    >
      <div class="quality-report">
        <div class="report-header">
          <h3>质量分析报告</h3>
          <p>报告生成时间：{{ new Date().toLocaleString() }}</p>
        </div>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div ref="reportChart1" class="report-chart"></div>
          </el-col>
          <el-col :span="12">
            <div ref="reportChart2" class="report-chart"></div>
          </el-col>
        </el-row>
        
        <div class="report-summary">
          <h4>质量总结</h4>
          <ul>
            <li>本月总检验次数：{{ qualityStats.totalInspections }}次</li>
            <li>合格率：{{ qualityStats.passRate }}%，较上月提升2.3%</li>
            <li>主要缺陷类型：外观缺陷占比45%，尺寸偏差占比30%</li>
            <li>改进建议：加强进料检验，优化生产工艺参数</li>
          </ul>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="qualityReportVisible = false">关闭</el-button>
          <el-button type="primary" @click="exportReport">导出报告</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import {
  Plus,
  Download,
  Document,
  CircleCheck,
  Warning,
  TrendCharts,
  Search,
  Refresh,
  ArrowDown
} from '@element-plus/icons-vue'

// 响应式数据
const activeTab = ref('inspection')
const inspectionDialogVisible = ref(false)
const qualityReportVisible = ref(false)
const inspectionFormRef = ref(null)

// 图表引用
const qualityTrendChart = ref(null)
const defectTypeChart = ref(null)
const reportChart1 = ref(null)
const reportChart2 = ref(null)

// 质量统计数据
const qualityStats = reactive({
  totalInspections: 1248,
  passRate: 96.8,
  defectCount: 42,
  improvementRate: 12.5
})

// 质检筛选表单
const inspectionFilter = reactive({
  inspectionNo: '',
  productName: '',
  inspectionType: '',
  status: ''
})

// 不合格品筛选表单
const defectFilter = reactive({
  defectNo: '',
  defectType: '',
  handleStatus: ''
})

// 分页
const inspectionPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const defectPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 质检单表单
const inspectionForm = reactive({
  inspectionNo: 'QC' + Date.now(),
  inspectionType: '',
  productName: '',
  batchNo: '',
  quantity: 100,
  sampleSize: 10,
  inspector: '',
  inspectionDate: new Date(),
  remarks: ''
})

// 表单验证规则
const inspectionRules = {
  inspectionType: [
    { required: true, message: '请选择检验类型', trigger: 'change' }
  ],
  productName: [
    { required: true, message: '请选择产品', trigger: 'change' }
  ],
  batchNo: [
    { required: true, message: '请输入批次号', trigger: 'blur' }
  ],
  inspector: [
    { required: true, message: '请选择检验员', trigger: 'change' }
  ]
}

// 质检单数据
const inspections = ref([
  {
    id: 1,
    inspectionNo: 'QC202501001',
    productName: '智能手机',
    batchNo: 'B20250115001',
    inspectionType: 'final',
    quantity: 100,
    sampleSize: 10,
    inspector: '张三',
    status: 'completed',
    result: 'pass',
    inspectionDate: '2025-01-15 14:30:00'
  },
  {
    id: 2,
    inspectionNo: 'QC202501002',
    productName: '平板电脑',
    batchNo: 'B20250115002',
    inspectionType: 'process',
    quantity: 50,
    sampleSize: 5,
    inspector: '李四',
    status: 'inspecting',
    result: null,
    inspectionDate: '2025-01-15 16:00:00'
  },
  {
    id: 3,
    inspectionNo: 'QC202501003',
    productName: '笔记本电脑',
    batchNo: 'B20250115003',
    inspectionType: 'incoming',
    quantity: 200,
    sampleSize: 20,
    inspector: '王五',
    status: 'failed',
    result: 'fail',
    inspectionDate: '2025-01-15 10:15:00'
  }
])

// 不合格品数据
const defects = ref([
  {
    id: 1,
    defectNo: 'DF202501001',
    productName: '智能手机',
    defectType: 'appearance',
    defectDescription: '外壳划痕',
    quantity: 5,
    severity: 'minor',
    handleStatus: 'pending',
    discoveryDate: '2025-01-15 14:30:00'
  },
  {
    id: 2,
    defectNo: 'DF202501002',
    productName: '平板电脑',
    defectType: 'dimension',
    defectDescription: '厚度超差',
    quantity: 3,
    severity: 'major',
    handleStatus: 'reworking',
    discoveryDate: '2025-01-15 16:00:00'
  }
])

// 质量标准数据
const qualityStandards = ref([
  {
    id: 1,
    standardCode: 'QS001',
    standardName: '智能手机外观质量标准',
    productCategory: '电子产品',
    version: '2.1',
    status: 'active',
    createDate: '2025-01-10 09:00:00'
  },
  {
    id: 2,
    standardCode: 'QS002',
    standardName: '电子产品功能测试标准',
    productCategory: '电子产品',
    version: '1.5',
    status: 'active',
    createDate: '2025-01-08 14:30:00'
  }
])

// 计算属性
const filteredInspections = computed(() => {
  let result = inspections.value
  
  if (inspectionFilter.inspectionNo) {
    result = result.filter(item => 
      item.inspectionNo.toLowerCase().includes(inspectionFilter.inspectionNo.toLowerCase())
    )
  }
  
  if (inspectionFilter.productName) {
    result = result.filter(item => 
      item.productName.toLowerCase().includes(inspectionFilter.productName.toLowerCase())
    )
  }
  
  if (inspectionFilter.inspectionType) {
    result = result.filter(item => item.inspectionType === inspectionFilter.inspectionType)
  }
  
  if (inspectionFilter.status) {
    result = result.filter(item => item.status === inspectionFilter.status)
  }
  
  inspectionPagination.total = result.length
  
  const start = (inspectionPagination.currentPage - 1) * inspectionPagination.pageSize
  const end = start + inspectionPagination.pageSize
  
  return result.slice(start, end)
})

const filteredDefects = computed(() => {
  let result = defects.value
  
  if (defectFilter.defectNo) {
    result = result.filter(item => 
      item.defectNo.toLowerCase().includes(defectFilter.defectNo.toLowerCase())
    )
  }
  
  if (defectFilter.defectType) {
    result = result.filter(item => item.defectType === defectFilter.defectType)
  }
  
  if (defectFilter.handleStatus) {
    result = result.filter(item => item.handleStatus === defectFilter.handleStatus)
  }
  
  defectPagination.total = result.length
  
  const start = (defectPagination.currentPage - 1) * defectPagination.pageSize
  const end = start + defectPagination.pageSize
  
  return result.slice(start, end)
})

// 工具函数
const getInspectionTypeText = (type) => {
  const typeMap = {
    incoming: '进料检验',
    process: '过程检验',
    final: '成品检验',
    outgoing: '出货检验'
  }
  return typeMap[type] || type
}

const getInspectionTypeColor = (type) => {
  const colorMap = {
    incoming: 'primary',
    process: 'success',
    final: 'warning',
    outgoing: 'info'
  }
  return colorMap[type] || 'info'
}

const getInspectionStatusText = (status) => {
  const statusMap = {
    pending: '待检验',
    inspecting: '检验中',
    completed: '已完成',
    failed: '不合格'
  }
  return statusMap[status] || status
}

const getInspectionStatusType = (status) => {
  const typeMap = {
    pending: 'warning',
    inspecting: 'primary',
    completed: 'success',
    failed: 'danger'
  }
  return typeMap[status] || 'info'
}

const getDefectTypeText = (type) => {
  const typeMap = {
    appearance: '外观缺陷',
    dimension: '尺寸偏差',
    function: '功能缺陷',
    material: '材料缺陷'
  }
  return typeMap[type] || type
}

const getDefectTypeColor = (type) => {
  const colorMap = {
    appearance: 'warning',
    dimension: 'danger',
    function: 'primary',
    material: 'info'
  }
  return colorMap[type] || 'info'
}

const getSeverityText = (severity) => {
  const severityMap = {
    minor: '轻微',
    major: '严重',
    critical: '致命'
  }
  return severityMap[severity] || severity
}

const getSeverityColor = (severity) => {
  const colorMap = {
    minor: 'success',
    major: 'warning',
    critical: 'danger'
  }
  return colorMap[severity] || 'info'
}

const getHandleStatusText = (status) => {
  const statusMap = {
    pending: '待处理',
    reworking: '返工中',
    scrapped: '已报废',
    completed: '已完成'
  }
  return statusMap[status] || status
}

const getHandleStatusType = (status) => {
  const typeMap = {
    pending: 'warning',
    reworking: 'primary',
    scrapped: 'danger',
    completed: 'success'
  }
  return typeMap[status] || 'info'
}

// 事件处理函数
const handleTabChange = (tabName) => {
  activeTab.value = tabName
}

const handleInspectionSearch = () => {
  inspectionPagination.currentPage = 1
}

const resetInspectionFilter = () => {
  Object.assign(inspectionFilter, {
    inspectionNo: '',
    productName: '',
    inspectionType: '',
    status: ''
  })
  handleInspectionSearch()
}

const handleDefectSearch = () => {
  defectPagination.currentPage = 1
}

const resetDefectFilter = () => {
  Object.assign(defectFilter, {
    defectNo: '',
    defectType: '',
    handleStatus: ''
  })
  handleDefectSearch()
}

const handleInspectionSelectionChange = (selection) => {
  console.log('选中的质检单:', selection)
}

const handleDefectSelectionChange = (selection) => {
  console.log('选中的不合格品:', selection)
}

const handleInspectionSizeChange = (size) => {
  inspectionPagination.pageSize = size
  inspectionPagination.currentPage = 1
}

const handleInspectionCurrentChange = (page) => {
  inspectionPagination.currentPage = page
}

const handleDefectSizeChange = (size) => {
  defectPagination.pageSize = size
  defectPagination.currentPage = 1
}

const handleDefectCurrentChange = (page) => {
  defectPagination.currentPage = page
}

const showCreateInspectionDialog = () => {
  inspectionForm.inspectionNo = 'QC' + Date.now()
  inspectionDialogVisible.value = true
}

const showQualityReportDialog = () => {
  qualityReportVisible.value = true
  nextTick(() => {
    initReportCharts()
  })
}

const viewInspection = (inspection) => {
  ElMessage.info(`查看质检单: ${inspection.inspectionNo}`)
}

const startInspection = (inspection) => {
  inspection.status = 'inspecting'
  ElMessage.success('检验已开始')
}

const completeInspection = (inspection) => {
  inspection.status = 'completed'
  inspection.result = 'pass'
  ElMessage.success('检验已完成')
}

const handleInspectionCommand = ({ action, row }) => {
  switch (action) {
    case 'edit':
      ElMessage.info(`编辑质检单: ${row.inspectionNo}`)
      break
    case 'print':
      ElMessage.success(`打印报告: ${row.inspectionNo}`)
      break
    case 'delete':
      deleteInspection(row)
      break
  }
}

const deleteInspection = (inspection) => {
  ElMessageBox.confirm(
    `确定要删除质检单 "${inspection.inspectionNo}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = inspections.value.findIndex(item => item.id === inspection.id)
    if (index > -1) {
      inspections.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const viewDefect = (defect) => {
  ElMessage.info(`查看不合格品: ${defect.defectNo}`)
}

const handleDefect = (defect) => {
  ElMessage.info(`处理不合格品: ${defect.defectNo}`)
}

const handleDefectCommand = ({ action, row }) => {
  switch (action) {
    case 'edit':
      ElMessage.info(`编辑不合格品: ${row.defectNo}`)
      break
    case 'rework':
      row.handleStatus = 'reworking'
      ElMessage.success('已安排返工')
      break
    case 'scrap':
      row.handleStatus = 'scrapped'
      ElMessage.success('已标记为报废')
      break
    case 'delete':
      deleteDefect(row)
      break
  }
}

const deleteDefect = (defect) => {
  ElMessageBox.confirm(
    `确定要删除不合格品记录 "${defect.defectNo}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = defects.value.findIndex(item => item.id === defect.id)
    if (index > -1) {
      defects.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const showCreateStandardDialog = () => {
  ElMessage.info('新建质量标准功能开发中')
}

const viewStandard = (standard) => {
  ElMessage.info(`查看质量标准: ${standard.standardName}`)
}

const editStandard = (standard) => {
  ElMessage.info(`编辑质量标准: ${standard.standardName}`)
}

const deleteStandard = (standard) => {
  ElMessageBox.confirm(
    `确定要删除质量标准 "${standard.standardName}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = qualityStandards.value.findIndex(item => item.id === standard.id)
    if (index > -1) {
      qualityStandards.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const saveInspection = () => {
  inspectionFormRef.value.validate((valid) => {
    if (valid) {
      const newInspection = {
        id: Date.now(),
        ...inspectionForm,
        status: 'pending',
        result: null,
        inspectionDate: inspectionForm.inspectionDate.toLocaleString()
      }
      inspections.value.unshift(newInspection)
      ElMessage.success('质检单创建成功')
      inspectionDialogVisible.value = false
    }
  })
}

const exportData = () => {
  ElMessage.success('数据导出功能开发中')
}

const exportReport = () => {
  ElMessage.success('报告导出功能开发中')
}

// 初始化图表
const initCharts = () => {
  // 质量趋势图表
  if (qualityTrendChart.value) {
    const trendChart = echarts.init(qualityTrendChart.value)
    const trendOption = {
      title: {
        text: '质量趋势',
        left: 'center',
        textStyle: { fontSize: 14 }
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['合格率', '检验次数'],
        bottom: 0
      },
      xAxis: {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月']
      },
      yAxis: [
        {
          type: 'value',
          name: '合格率(%)',
          position: 'left'
        },
        {
          type: 'value',
          name: '检验次数',
          position: 'right'
        }
      ],
      series: [
        {
          name: '合格率',
          type: 'line',
          yAxisIndex: 0,
          data: [94.5, 95.2, 96.1, 95.8, 96.8, 97.2],
          itemStyle: { color: '#67C23A' }
        },
        {
          name: '检验次数',
          type: 'bar',
          yAxisIndex: 1,
          data: [180, 220, 195, 210, 248, 265],
          itemStyle: { color: '#409EFF' }
        }
      ]
    }
    trendChart.setOption(trendOption)
  }

  // 缺陷类型分布图表
  if (defectTypeChart.value) {
    const defectChart = echarts.init(defectTypeChart.value)
    const defectOption = {
      title: {
        text: '缺陷类型分布',
        left: 'center',
        textStyle: { fontSize: 14 }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '缺陷类型',
          type: 'pie',
          radius: '50%',
          data: [
            { value: 45, name: '外观缺陷' },
            { value: 30, name: '尺寸偏差' },
            { value: 15, name: '功能缺陷' },
            { value: 10, name: '材料缺陷' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    defectChart.setOption(defectOption)
  }
}

const initReportCharts = () => {
  // 报告图表1
  if (reportChart1.value) {
    const chart1 = echarts.init(reportChart1.value)
    const option1 = {
      title: {
        text: '月度质量趋势',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月']
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '合格率',
          type: 'line',
          data: [94.5, 95.2, 96.1, 95.8, 96.8, 97.2],
          smooth: true,
          itemStyle: { color: '#67C23A' }
        }
      ]
    }
    chart1.setOption(option1)
  }

  // 报告图表2
  if (reportChart2.value) {
    const chart2 = echarts.init(reportChart2.value)
    const option2 = {
      title: {
        text: '缺陷分析',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      series: [
        {
          name: '缺陷分布',
          type: 'pie',
          radius: '60%',
          data: [
            { value: 45, name: '外观缺陷' },
            { value: 30, name: '尺寸偏差' },
            { value: 15, name: '功能缺陷' },
            { value: 10, name: '材料缺陷' }
          ]
        }
      ]
    }
    chart2.setOption(option2)
  }
}

// 生命周期
onMounted(() => {
  nextTick(() => {
    initCharts()
  })
})
</script>

<style scoped>
.quality-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.header-left h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.header-left p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.header-right {
  display: flex;
  gap: 12px;
}

.stats-overview {
  margin-bottom: 20px;
}

.stats-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stats-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stats-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.stats-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stats-icon.pass {
  background: linear-gradient(135deg, #67C23A 0%, #85ce61 100%);
}

.stats-icon.defect {
  background: linear-gradient(135deg, #F56C6C 0%, #f78989 100%);
}

.stats-icon.improvement {
  background: linear-gradient(135deg, #409EFF 0%, #66b1ff 100%);
}

.stats-info {
  flex: 1;
}

.stats-number {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
}

.stats-label {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
}

.charts-row {
  margin-bottom: 20px;
}

.chart-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chart-container {
  height: 300px;
  width: 100%;
}

.tabs-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.tab-content {
  padding: 20px 0;
}

.filter-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.standard-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.quality-report {
  padding: 20px 0;
}

.report-header {
  text-align: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.report-header h3 {
  margin: 0 0 10px 0;
  color: #303133;
}

.report-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.report-chart {
  height: 300px;
  width: 100%;
}

.report-summary {
  margin-top: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.report-summary h4 {
  margin: 0 0 15px 0;
  color: #303133;
}

.report-summary ul {
  margin: 0;
  padding-left: 20px;
}

.report-summary li {
  margin-bottom: 8px;
  color: #606266;
  line-height: 1.6;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .quality-management {
    padding: 12px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .header-right {
    width: 100%;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
  
  .charts-row {
    flex-direction: column;
  }
  
  .filter-section .el-form {
    flex-direction: column;
  }
  
  .filter-section .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
  }
}
</style>